import { defineStore } from 'pinia'
import { TabsMenuProps } from '@/store/interface'
import { TABS_WHITE_LIST } from '@/config/config'
import piniaPersistConfig from '@/config/piniaPersist'
import router from '@/router/index'

// TabsStore
export const TabsStore = defineStore('TabsState', {
  state: () => {
    return {
      tabsMenuList: <TabsMenuProps[]>[]
    }
  },
  getters: {},
  actions: {
    // Add Tabs
    async addTabs(tabItem: TabsMenuProps) {
      // not add tabs white list
      if (TABS_WHITE_LIST.includes(tabItem.path)) return
      if (this.tabsMenuList.every((item: { path: any }) => item.path !== tabItem.path)) {
        this.tabsMenuList.push(tabItem)
      }
    },
    // Remove Tabs
    async removeTabs(tabPath: string, isCurrent = true) {
      const tabsMenuList = this.tabsMenuList
      if (isCurrent) {
        tabsMenuList.forEach((item: { path: string }, index: number) => {
          if (item.path !== tabPath) return
          const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1]
          if (!nextTab) return
          router.push(nextTab.path)
        })
      }
      this.tabsMenuList = tabsMenuList.filter((item: { path: string }) => item.path !== tabPath)
    },
    // Close MultipleTab
    async closeMultipleTab(tabsMenuValue?: string) {
      this.tabsMenuList = this.tabsMenuList.filter((item: { path: string | undefined; close: any }) => {
        return item.path === tabsMenuValue || !item.close
      })
    }
  },
  persist: piniaPersistConfig('TabsState')
})
